Join or Concatenate Strings with Comma in Java
π€Ή Java String Joining Fun! πβ
Hey there, Java ninjas! π₯ Today, weβre diving into the world of string concatenation. But waitβthis isn't your boring old textbook tutorial. Weβre going to make string joining as exciting as assembling your dream burger! π
Ever found yourself needing to glue together an array of strings, especially when dealing with JSON, XML, or just some fancy output formatting? Well, sit tight because weβve got you covered! π
π― 1. Java 8 β Using String.join()
β
Java 8 brought us some cool tools, and String.join()
is one of them! Think of it as the duct tape for your strings. π οΈ
πΉ 1.1. Join String Literalsβ
If your strings are all over the place, this method lets you tie them together in one neat package.
String joinedString = String.join(",", "How", "To", "Do", "In", "Java");
System.out.println(joinedString); // How,To,Do,In,Java
β¨ Boom! Instant list without even using an array.
πΉ 1.2. Joining an Array or Listβ
Got a string herd (a.k.a. an array)? Round them up into one!
String[] strArray = { "How", "To", "Do", "In", "Java" };
String joinedString = String.join(",", strArray);
System.out.println(joinedString); // How,To,Do,In,Java
π¨ 2. Java 8 β StringJoiner
for Fancy Outputβ
If you like your output well-dressed, StringJoiner
is here to give it some pizzazz. β¨
πΉ 2.1. Syntax Magicβ
Think of StringJoiner
as a personal stylist for your stringsβadding delimiters, prefixes, and suffixes.
StringJoiner joiner = new StringJoiner("," ,"[", "]");
String joinedString = joiner.add("How")
.add("To")
.add("Do")
.add("In")
.add("Java")
.toString();
System.out.println(joinedString); // [How,To,Do,In,Java]
π 3. Java 8 β Collectors.joining()
for Stream Loversβ
Are you into functional programming and streams? Well, Java has got your back! πͺ
List<String> tokens = Arrays.asList("How", "To", "Do", "In", "Java");
String joinedString = tokens.stream()
.collect(Collectors.joining(",", "[", "]"));
System.out.println(joinedString); // [How,To,Do,In,Java]
π‘ Perfect for handling lists in a breeze!
π οΈ 4. Apache Commons β StringUtils.join()
β
If youβre a power user, the Apache Commons library has some next-level string manipulation tools. π¦ΈββοΈ
First, add this to your Maven dependencies:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.12.0</version>
</dependency>
πΉ 4.1. Joining Like a Proβ
String[] strArray = { "How", "To", "Do", "In", "Java" };
String joinedString = StringUtils.join(strArray);
System.out.println(joinedString); // HowToDoInJava
String joinedString2 = StringUtils.join(strArray, ",");
System.out.println(joinedString2); // How,To,Do,In,Java
π Super fast, super easy!
π Wrapping Upβ
No matter how you like your string sandwich, Java has tons of ways to help you join your ingredients together! π₯ͺ
If you have questions, thoughts, or just want to share your favorite joke, drop them in the comments! ππ
Happy Coding! π¨βπ»π